import React from 'react';
import axios from 'axios'
import {store} from './store'
import { add, addTo, reduce, getList } from './store/action'
console.log(store.getState())

class App extends React.Component {
  constructor() {
    super()
    this.state = {
      num: 0,
      lists: []
    } 
  }
  //函数柯里化，js高阶函数
  add = (_num) => (e) => {
    store.dispatch(addTo(_num))
  }

  newReduce = (num) => (e) => {
    store.dispatch(reduce(num))
  }
  
  update = () => {
    const { num,lists } = store.getState()
    this.setState({
      num,
      lists
    })
  } 
  getLists = () => {
    axios.get('https://pc.raz-kid.cn/api').then(
      res => {
        store.dispatch(getList(res.data.data.topicList))
      }
    )
  }
  componentDidMount() {
    this.handleUpdate = store.subscribe(this.update)
    this.getLists()
  }
  componentWillUnmount() {
    this.handleUpdate()
  }
  render() {
    const {add, newReduce} = this
    const { lists, num} = this.state
    return (
      <div>
        <button num={-1} onClick={newReduce(1)}>-</button>
        {num}
        <button num={1} onClick={add(1)}>+</button>
        <ul>
          {lists.length > 0 ? lists.map(item => <li key={item.id}>{item.title}</li>):''}
        </ul>
      </div>
    )
  }
}

export default App;
